package com.ybear.ybcomponent.widget.dialog

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.util.Consumer
import androidx.fragment.app.FragmentActivity

/**
 * 弹窗相关权限申请
 */
class DialogPermission {
    companion object {
        private const val REQUEST_CODE_OVERLAY_PERMISSION = 1800001
        @JvmStatic
        private val i by lazy { DialogPermission() }
        @JvmStatic
        fun get() : DialogPermission { return i }
    }

    private var callOverlayPermission: Consumer<Boolean>? = null

    /**
     * 发起系统级弹窗权限申请
     */
    @JvmOverloads
    fun applyOverlayPermission(fa: FragmentActivity, call: Consumer<Boolean>? = null) : Boolean {
        if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays( fa ) ) {
            callOverlayPermission = call
            // 需要悬浮窗权限，但没有授予则跳转到应用权限设置页面
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:${fa.packageName}")
            )
            fa.startActivityForResult( intent, REQUEST_CODE_OVERLAY_PERMISSION )
            return false
        } else {
            // 不需要悬浮窗权限，或者已经授予
            call?.accept( true )
            callOverlayPermission = null
            return true
        }
    }

    fun onActivityResult(fa: FragmentActivity, requestCode: Int, resultCode: Int, data: Intent?) {
        when( requestCode ) {
            //统级弹窗权限申请结果
            REQUEST_CODE_OVERLAY_PERMISSION -> {
                //返回授权结果
                callOverlayPermission?.accept(
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays( fa )
                )
            }
        }
    }
}